#include <linux/proc_fs.h>
#include <linux/init.h>
#include <asm/uaccess.h>
#include <linux/string.h>
#include <linux/gpio.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/irqreturn.h>
#include <linux/module.h>
#include <linux/device.h>


static int major;
static unsigned char buff[100];
static struct class *led_class;

/*led args*/
//unsigned int led_gpio = 129;    //对照原理图  蜂鸣器
//unsigned int led_gpio = 18;     //对照原理图  按键
unsigned int led_gpio = 3;        //对照原理图       led


static int led_open (struct inode *node, struct file *filp)
{
	printk("led_open\n");
	printk("%s %s %d\n",__FILE__, __FUNCTION__, __LINE__);

	return 0;
}

static ssize_t led_read (struct file *filp, char *buf, size_t size, loff_t *offset)
{
	printk("led_drv_read\n");

	/*read led_gpio value*/
	buff[0] = gpio_get_value(led_gpio);
	
	copy_to_user(buf, buff, 1);

	//返回什么不重要，也可以直接返回gpio的值，但是最好还是按照驱动程序模式来写，使用copy_to_user
	return buff[0];  
}

static ssize_t led_write (struct file *filp, const char *buf, size_t size, loff_t *offset)
{
	printk("led_drv_write\n");
	copy_from_user(buff, buf, 1);
	
	/*write led_gpio*/
	gpio_set_value(led_gpio, buff[0]);
	
	return led_gpio;
}

static int led_release (struct inode *node, struct file *filp)
{
	printk("led_release\n");
	return 0;
}

/*1.定义 file_operations 结构体*/
static const struct file_operations led_fops = {
    .owner 		= THIS_MODULE,
	.read		= led_read,
	.write		= led_write,
	.open		= led_open,
	.release    = led_release,
};


/*2.register_chrdev*/

/*3.入口函数*/
static int led_init(void)
{
	struct device *dev;
	int err;

	/************* 1.注册设备，返回设备号 ************/
	major = register_chrdev(0,"led_drv",&led_fops);

	/*2.在内核中创建设备*/
	led_class = class_create(THIS_MODULE, "led_class");
	if (IS_ERR(led_class)) {
		printk("led class create failed!\n");
	}

	/*3.在/dev下面创建设备节点*/
	device_create(led_class, NULL, MKDEV(major, 0), NULL, "led_drv");
	if(IS_ERR(dev)) {
		printk("led device_create  failed!\n");
	}

	/************* 4.初始化led引脚 ************/
	/*申请led_gpio引脚*/
	err = gpio_request(led_gpio, "user_led");
	if(err < 0){
		printk("led gpio request failed!\n");
		return -ENODEV;
	}
	
	/*设置led_gpio输出模式*/
	gpio_direction_output(led_gpio, 1);
	
	return 0;
}

/*4.退出函数*/
static void led_exit(void)
{
	//卸载设备
	unregister_chrdev(major,"led_fops");

	//销毁设备
	device_destroy(led_class, MKDEV(major, 0));
	//删除设备类
	class_destroy(led_class);

	/*释放led_gpio引脚*/
	gpio_free(led_gpio);
	printk("led_exit\n");

}	

module_init(led_init);
module_exit(led_exit);
MODULE_LICENSE("GPL");

